package com.tjhk.java.tech.thread;

import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;
import java.util.stream.IntStream;

public class CacheThreadPool3 {
    public static Integer extractResult(Future<Integer> f){
        try {
            return f.get();
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } catch (ExecutionException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) throws RuntimeException, InterruptedException {
        ExecutorService exec = Executors.newCachedThreadPool();
        List<CountingTask> tasks
                = IntStream.range(0,30).mapToObj(CountingTask::new).collect(Collectors.toList());
        List<Future<Integer>> futures = exec.invokeAll(tasks);
        Integer sum = futures.stream().map(CacheThreadPool3::extractResult)
                .reduce(0,Integer::sum);
        System.out.println(sum);
        exec.shutdown();


        System.out.println(
                IntStream.range(0,30).mapToObj(i->new CountingTask(i*i)).map(cl-> {
                    try {
                        return cl.call();
                    } catch (Exception e) {
                        throw new RuntimeException(e);
                    }
                }).reduce(0,Integer::sum)
        );

    }
}
